import store from '../store/index.js'
import utils from './utils.js'
const app_info = require("@/common/appInfo.js");
const api_host = app_info.api_host

function req(obj) {
	return new Promise((resolve, reject) => {
		console.log(obj, 'obj')
		const HOST = api_host
		var method = obj.method || "GET";
		var url = "";
		var header = "";
		if (obj.third) {
			url = obj.url
			header = Object.assign(obj.header, {
				'Content-Type': 'application/json'
			})
			console.log(header, 'header')
		} else {
			url = HOST + obj.url
			header = {
				'Content-Type': 'application/json' //application/x-www-form-urlencoded  application/json
			}
		}

		var data = obj.data || {};

		if (uni.getStorageSync('token')) {
			header.Authorization = uni.getStorageSync('token')
		}
		var success = obj.success; // 成功回调函数
		var fail = obj.fail; //表示失败后，要执行的回调函数

		uni.request({
			url: url,
			data: data,
			method: method,
			header: header,
			timeout: 180000,
			success: ((res) => {
				if (res.data.code == 200 || res.data.code == 1 || res.data.code == 201) { //请求成功
					resolve(res.data);
				} else if (res.data.code == 401) {
					//uni.removeStorageSync('token')
					store.commit('logOut')
					utils.wxLogin()
					return false
				} else if (res.data.code == 505) {
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: res.data.msg
					});
					resolve(res.data);
				} else {
					resolve(res.data);
					uni.showToast({
						icon: 'none',
						duration: 3000,
						title: res.data.msg || '网络出现故障，请稍后再试'
					});
				}
			}),
			fail: ((err) => {
				console.log(2222, err);
				reject(err)
			}),
			complete: (() => {
				//uni.hideLoading()
			})
		})

	})
}
export default req